import datetime
import logging

import pytest
import requests
import yaml
from faker import Faker


def pytest_collection_modifyitems(items):
    """
    处理中文的unicode显示问题
    :return:
    """
    for item in items:
        item.name = item.name.encode("utf-8").decode("unicode_escape")
        item._nodeid = item.nodeid.encode("utf-8").decode("unicode_escape")


@pytest.fixture(scope='session')
def get_token() -> str:
    """
    获取token字符串
    如果本地token仍然有效则使用本地token；
    如果本地token失效则重新获取并更新。
    """
    logging.info("------ 读取本地token ------")
    with open('../local/token.yaml', 'r', encoding='utf-8') as f:
        token_loc = yaml.safe_load(f)

    now_timestamp = int(datetime.datetime.now().timestamp())
    if now_timestamp >= token_loc.get('expiry_deadline'):

        logging.info("------ 本地token已失效，重新请求token ------")
        corp_id = token_loc.get('ios_corp_id')
        corp_secret = token_loc.get('ios_corp_secret')
        url = f"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corp_id}&corpsecret={corp_secret}"
        resp = requests.get(url).json()

        token = resp.get('access_token')    # 提取token
        duration = resp.get('expires_in')    # 提取duration
        expiry_deadline = int(datetime.datetime.now().timestamp()) + duration   # 推算下一个失效时间戳
        expiry_remark = datetime.datetime.fromtimestamp(expiry_deadline).strftime('%Y-%m-%d %H:%M:%S')

        logging.info("------ 更新token对象 ------")
        token_loc.update({'token': token,
                          'duration': duration,
                          'expiry_deadline': expiry_deadline,
                          'expiry_remark': expiry_remark})

        logging.info("------ 保存新token到本地 ------")
        with open('../local/token.yaml', 'w', encoding='utf-8') as f:
            yaml.safe_dump(token_loc, f)
    else:
        logging.info("------ 正在使用本地存储到token ------")
        token = token_loc.get('token')

    yield token
